package com.ts.auth.controller;


import com.ts.auth.dto.UserLoginDto;
import com.ts.auth.vo.UserLoginVo;
import com.ts.common.core.exception.TSException;
import com.ts.common.core.utils.JWTUtils;
import com.ts.common.core.utils.Result;
import com.ts.feign.api.UserService;
import com.ts.feign.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

;

@RestController
public class UserLoginController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    public String SMSKey = "ts:notice:login:%s-%s";

    @PostMapping("/login")
    public Result login(@RequestBody UserLoginVo userLoginVo){

        String phone = userLoginVo.getPhone();
        String code = userLoginVo.getCode();

        //判断手机号是否为空
        if(phone.isEmpty()){
            throw new TSException("手机号不能为空");
        }

        if (code.isEmpty()){
            throw new TSException("验证码不能为空");
        }

        String Key = String.format(SMSKey,phone,code);

        //直接删除redis中登录的数据，解决了原子性问题；
        Boolean flag = redisTemplate.delete(Key) ;

        if (!flag){
            throw new TSException("验证码有误");
        }
        //到这里就表明验证成功了
        //判断手机号是否注册了
        UserDTO userDTO = userService.getUserByPhone(phone);
        if (userDTO == null){
            //进入这里表示当前用户还没注册
            userDTO = new UserDTO();
            userDTO.setPhone(phone);
            String phoneEnd = phone.substring(phone.length() - 4);
            userDTO.setUsername("Ts-"+phoneEnd);
            userDTO.setIntegral(100);
            userDTO = userService.addUser(userDTO);

        }
        userDTO.setPhone(null);
        userDTO.setOpenid(null);
        userDTO.setStatus(null);
        UserLoginDto userLoginDto = new UserLoginDto();
        userLoginDto.setUserId(userDTO.getId());
        userLoginDto.setCreateTime(new Date());
        //获取token
        String token = JWTUtils.getToken("loginUser", userLoginDto);

        //将返回的数据封装的map中
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);

        map.put("userInfo",userDTO);

        return new Result().Viewok(map);
    }



}
